from apps.utils.http_request import HTTP
from flask import current_app


class YuShuBook:
    keyword_url = 'http://t.yushu.im/v2/book/search?q={}&count={}&start={}'
    isbn_url = 'http://t.yushu.im/v2/book/isbn/{}'

    def __init__(self):
        self.count = 0
        self.books = []

    def search_by_word(self, word, page):
        url = self.keyword_url.format(word, current_app.config['PER_PAGE'], self.get_start(page))
        resp = HTTP.get(url)
        self.__fill_multiple(resp)

    def search_by_isbn(self, isbn):
        url = self.isbn_url.format(isbn)
        resp = HTTP.get(url)
        self.__fill_single(resp)

    def get_start(self, page):
        return (page - 1) * current_app.config['PER_PAGE']

    def __fill_single(self, data):
        if data:
            self.count = 1
            self.books.append(data)

    def __fill_multiple(self, data):
        if data:
            self.count = data['count']
            self.books = data['books']

    @property
    def first(self):
        return self.books[0] if len(self.books) > 0 else None
